import { getGPABySid,getHonorsByKeyword } from "../../api/manage";

Page({
  data: {
    terms: [], // 学期列表
    honors: [{ title: '无' }], // 荣誉列表
    gpas: [], // 学分绩列表
    selectedTerm: null // 选中的学期
  },

  onLoad: function() {
    this.calculateTerms();
    this.loadGPA();
  },

  calculateTerms: function() {
    const enrollmentDate = new Date('2021-09-01'); // 学生入学日期
    const today = new Date(); // 当前日期
    let terms = [];
    let startYear = enrollmentDate.getFullYear(); // 入学年份
    let month = enrollmentDate.getMonth() + 1; // 获取入学月份

    let currentTermStart = new Date(enrollmentDate); // 当前学期开始日期

    // 计算学期
    while (currentTermStart <= today) {
      let semesterYear = startYear;
      let termType = '上学期';
      if (month >= 3&&month <= 8) {
        termType = '下学期';
      }

      let semester = `${semesterYear}-${semesterYear + 1}${termType}`;
      terms.push(semester);

      // 更新到下一个学期
      if (termType === '上学期') {
        // 上学期结束后进入下学期
        currentTermStart.setMonth((currentTermStart.getMonth() + 6)%12);
      } else {
        // 下学期结束后进入下一个学年的上学期
        currentTermStart.setFullYear(currentTermStart.getFullYear() + 1);
        currentTermStart.setMonth(8); // 9月
        startYear++; // 年份增加
      }

      // 更新年份和月份
      startYear = currentTermStart.getFullYear();
      month = currentTermStart.getMonth() + 1;

      // 检查是否超过当前日期
      if (currentTermStart > today) {
        break;
      }
    }

    this.setData({ terms: terms });
  },

  selectTerm: function(e) {
    const userID = wx.getStorageSync('userID');

    getHonorsByKeyword(userID,e.currentTarget.dataset.term).then(res => {
      if (res.data.length === 0) {
        this.setData({ honors: [{ title: '无' }] });
      }
      else{
        const processedData = res.data.map(item => {
          return {
            ...item,
            title: `${item.honorName}`
          };
        });
        // 将处理后的数据设置到页面的data中
        this.setData({ honors: processedData });
      }
    });
  },

  loadGPA:function(){
    const userID = wx.getStorageSync('userID');
    getGPABySid(userID).then(res => {
      const processedData = res.data.map(item => {
        return {
          ...item,
          gpaInfo: `${item.schoolYear} : ${item.gpa}`
        };
      });
      // 将处理后的数据设置到页面的data中
      this.setData({ gpas: processedData });
    }).catch(err => {console.log("获取学分绩失败")});
  }
});